from flask import Flask, render_template, request, jsonify
import re
import json
import os
import glob

app = Flask(__name__)

# 错题库文件路径
WRONG_QUESTIONS_FILE = 'wrong_questions.json'

# 获取所有题库文件
def get_question_files():
    """获取所有txt题库文件"""
    # 修改为在题库子目录中查找
    txt_files = glob.glob('题库/*.txt')
    question_files = []
    for file in txt_files:
        # 提取文件显示名称（去掉路径和扩展名）
        display_name = os.path.basename(file).replace('.txt', '').replace(' (1)', '')
        question_files.append({
            'filename': file,
            'display_name': display_name
        })
    return question_files

# 读取题库文件
def load_questions(filename='电工高级（单项与判断） (1).txt'):
    questions = []
    
    if not os.path.exists(filename):
        return questions
    
    with open(filename, 'r', encoding='utf-8') as f:
        content = f.read()
    
    # 按空行分割题目块
    question_blocks = content.split('\n\n')
    
    # 处理每个题目块
    for i, block in enumerate(question_blocks):
        if not block.strip():
            continue
            
        lines = [line.strip() for line in block.strip().split('\n') if line.strip()]
        
        if len(lines) < 3:  # 至少需要题目、答案、解析
            continue
        
        # 提取题目内容（第一行）
        content_text = lines[0]
        
        # 提取选项
        options = []
        answer = ''
        explanation = '暂无解析'
        
        for line in lines[1:]:
            if line.startswith(('A、', 'B、', 'C、', 'D、', 'E、')):
                key, value = line.split('、', 1)
                options.append({'key': key, 'value': value})
            elif line.startswith('答案：'):
                answer = line[3:].strip()
            elif line.startswith('解析：'):
                explanation = line[3:].strip()
        
        # 判断题型
        is_judgment = False
        is_multiple_choice = False
        
        if len(options) == 2:
            option_values = [opt['value'] for opt in options]
            if any('正确' in val for val in option_values) and any('错误' in val for val in option_values):
                is_judgment = True
        
        # 检查是否为多选题（答案包含多个字母）
        if len(answer) > 1 and all(c in 'ABCDE' for c in answer):
            is_multiple_choice = True
        
        # 创建题目对象
        if content_text and answer and options:
            if is_judgment:
                question_type = '判断题'
            elif is_multiple_choice:
                question_type = '多选题'
            else:
                question_type = '单选题'
                
            question = {
                'id': len(questions) + 1,
                'content': content_text,
                'options': options,
                'answer': answer,
                'explanation': explanation,
                'type': question_type,
                'source_file': filename  # 添加来源文件信息
            }
            
            questions.append(question)
    
    return questions

# 批量加载所有题库文件
def load_all_question_files():
    """加载所有题库文件并合并题目"""
    all_questions = []
    question_files = get_question_files()
    
    for file_info in question_files:
        filename = file_info['filename']
        display_name = file_info['display_name']
        
        print(f"正在加载题库: {display_name}")
        questions = load_questions(filename)
        
        # 为每个题目添加来源信息
        for question in questions:
            question['source_file'] = filename
            question['source_display_name'] = display_name
        
        all_questions.extend(questions)
        print(f"已加载 {len(questions)} 道题目")
    
    print(f"总共加载了 {len(all_questions)} 道题目")
    return all_questions

# 获取题库统计信息
def get_question_statistics():
    """获取所有题库的统计信息"""
    question_files = get_question_files()
    statistics = []
    
    for file_info in question_files:
        filename = file_info['filename']
        display_name = file_info['display_name']
        
        questions = load_questions(filename)
        
        # 统计题型分布
        type_counts = {}
        for question in questions:
            q_type = question['type']
            type_counts[q_type] = type_counts.get(q_type, 0) + 1
        
        statistics.append({
            'filename': filename,
            'display_name': display_name,
            'total_questions': len(questions),
            'type_distribution': type_counts
        })
    
    return statistics

# 默认加载第一个题库
current_question_file = '题库/电工高级（单项与判断） (1).txt'
questions = load_questions(current_question_file)

# 加载错题库
def load_wrong_questions():
    if os.path.exists(WRONG_QUESTIONS_FILE):
        try:
            with open(WRONG_QUESTIONS_FILE, 'r', encoding='utf-8') as f:
                return json.load(f)
        except:
            return []
    return []

# 保存错题库
def save_wrong_questions(wrong_questions):
    with open(WRONG_QUESTIONS_FILE, 'w', encoding='utf-8') as f:
        json.dump(wrong_questions, f, ensure_ascii=False, indent=2)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/api/questions', methods=['GET'])
def get_questions():
    return jsonify(questions)

@app.route('/api/question/<int:question_id>', methods=['GET'])
def get_question(question_id):
    if 1 <= question_id <= len(questions):
        return jsonify(questions[question_id-1])
    else:
        return jsonify({"error": "问题不存在"}), 404

@app.route('/api/check', methods=['POST'])
def check_answer():
    data = request.get_json()
    question_id = data.get('questionId')
    user_answer = data.get('answer')
    
    if 1 <= question_id <= len(questions):
        question = questions[question_id-1]
        
        # 对于多选题，需要将答案字符排序后比较
        if question['type'] == '多选题':
            correct_answer = ''.join(sorted(question['answer']))
            user_answer_sorted = ''.join(sorted(user_answer))
            correct = correct_answer == user_answer_sorted
        else:
            correct = question['answer'] == user_answer
            
        return jsonify({
            'correct': correct,
            'correctAnswer': question['answer'],
            'explanation': question['explanation']
        })
    else:
        return jsonify({"error": "问题不存在"}), 404

@app.route('/api/wrong-questions', methods=['GET'])
def get_wrong_questions():
    wrong_questions = load_wrong_questions()
    return jsonify(wrong_questions)

@app.route('/api/wrong-questions', methods=['POST'])
def add_wrong_question():
    wrong_questions = load_wrong_questions()
    new_question = request.get_json()
    
    # 检查题目是否已经在错题库中（同时检查ID和来源文件）
    question_exists = any(
        q['id'] == new_question['id'] and 
        q.get('source_file', '') == new_question.get('source_file', '')
        for q in wrong_questions
    )
    
    if not question_exists:
        wrong_questions.append(new_question)
        save_wrong_questions(wrong_questions)
    
    return jsonify({"message": "添加成功"}), 200

@app.route('/api/wrong-questions/<int:question_id>', methods=['DELETE'])
def remove_wrong_question(question_id):
    wrong_questions = load_wrong_questions()
    # 获取请求数据中的来源文件信息
    data = request.get_json() if request.get_json() else {}
    source_file = data.get('source_file', current_question_file)
    
    # 删除指定ID和来源文件的错题
    wrong_questions = [
        q for q in wrong_questions 
        if not (q['id'] == question_id and q.get('source_file', '') == source_file)
    ]
    save_wrong_questions(wrong_questions)
    return jsonify({"message": "删除成功"}), 200

@app.route('/api/wrong-questions/current', methods=['DELETE'])
def clear_current_wrong_questions():
    """清空当前题库的错题"""
    wrong_questions = load_wrong_questions()
    # 只删除当前题库文件的错题
    wrong_questions = [
        q for q in wrong_questions 
        if q.get('source_file', '') != current_question_file
    ]
    save_wrong_questions(wrong_questions)
    return jsonify({"message": "当前题库错题已清空"}), 200

@app.route('/api/wrong-questions/all', methods=['DELETE'])
def clear_wrong_questions():
    """清空所有错题"""
    save_wrong_questions([])
    return jsonify({"message": "错题库已清空"}), 200

@app.route('/api/question-files', methods=['GET'])
def get_question_files_api():
    """获取可用的题库文件列表"""
    return jsonify(get_question_files())

@app.route('/api/switch-question-file', methods=['POST'])
def switch_question_file():
    """切换题库文件"""
    global questions, current_question_file
    
    data = request.get_json()
    filename = data.get('filename')
    
    if not filename or not os.path.exists(filename):
        return jsonify({"error": "文件不存在"}), 404
    
    # 加载新的题库
    questions = load_questions(filename)
    current_question_file = filename
    
    return jsonify({
        "message": "切换成功",
        "filename": filename,
        "question_count": len(questions)
    })

@app.route('/api/current-question-file', methods=['GET'])
def get_current_question_file():
    """获取当前题库文件信息"""
    return jsonify({
        "filename": current_question_file,
        "question_count": len(questions)
    })

@app.route('/api/question-statistics', methods=['GET'])
def get_question_statistics_api():
    """获取所有题库的统计信息"""
    statistics = get_question_statistics()
    return jsonify(statistics)

@app.route('/api/load-all-questions', methods=['GET'])
def load_all_questions_api():
    """加载所有题库文件并返回合并的题目列表"""
    all_questions = load_all_question_files()
    return jsonify({
        "total_questions": len(all_questions),
        "questions": all_questions
    })

if __name__ == '__main__':
    # 配置为局域网访问
    # host='0.0.0.0' 允许所有IP访问（包括局域网）
    # port=5000 指定端口号
    # debug=True 开启调试模式（生产环境建议关闭）
    app.run(host='0.0.0.0', port=5000, debug=True)
    
    # 如果只想本机访问，使用：app.run(debug=True)
    # 如果要指定特定IP，使用：app.run(host='192.168.1.100', port=5000) 